package main

import (
	"context"
	"log"
	"net"

	pb "neu/liuhy/gorpc/proto"

	"time"

	"google.golang.org/grpc"
	"google.golang.org/grpc/keepalive"
)

// 实现Greeter服务接口
type server struct {
	pb.UnimplementedBookServiceServer
}

func (s *server) FindBook(ctx context.Context, in *pb.BookRequest) (*pb.BookReply, error) {
	id := in.Id
	name := in.Name
	auth := in.Author
	log.Printf("Received GetBook: %v %v %v", name, id, auth)
	return &pb.BookReply{Name: "find a book " + name}, nil
}
func (s *server) GetBookList(ctx context.Context, in *pb.BookListRequest) (*pb.BookListReply, error) {
	id := in.Id
	name := in.Name
	auth := in.Author
	page := in.Page
	log.Printf("Received FindBook: %v %v %v %v ", name, id, auth, page)
	books := make([]*pb.BookReply, 0)
	for i := 0; i < 10; i++ {
		books = append(books, &pb.BookReply{Name: "find a book " + name})
	}
	return &pb.BookListReply{Books: books}, nil
}

func (s *server) AddBook(ctx context.Context, in *pb.BookRequest) (*pb.BookReply, error) {
	id := in.Id
	name := in.Name
	auth := in.Author
	log.Printf("Received CreateBook: %v %v %v", name, id, auth)
	return &pb.BookReply{Name: "create a book " + name}, nil
}
func main() {
	// 监听50051端口
	lis, err := net.Listen("tcp", ":50051")
	if err != nil {
		log.Fatalf("failed to listen: %v", err)
	}

	// 创建gRPC服务器
	s := grpc.NewServer(

		grpc.MaxConcurrentStreams(1000),
		grpc.KeepaliveParams(keepalive.ServerParameters{
			MaxConnectionIdle:     30 * time.Second, // 连接空闲 30s 触发保活
			MaxConnectionAge:      2 * time.Hour,    // 连接最大存活 2h，避免长期占用
			MaxConnectionAgeGrace: 5 * time.Minute,  // 存活期到后， grace 时间内处理完请求
			Time:                  10 * time.Second, // 每 10s 发一次保活探测
			Timeout:               5 * time.Second,  // 探测超时时间
		}),
	)

	// 注册Greeter服务
	pb.RegisterBookServiceServer(s, &server{})

	log.Println("Server listening at", lis.Addr())

	// 启动服务器
	if err := s.Serve(lis); err != nil {
		log.Fatalf("failed to serve: %v", err)
	}
}
